<?php 
namespace app\wework\model\user\send;
use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;

/**
* 流失提醒
**/
class GroupSendModel {
	static public $wid;

	/**
	 * 客户群群发列表
	 * @param page 页码
	 * @param times 发送时间
	 * @return
 	*/
	static public function getList($page,$times,$name,$size){
		$wid = Session::get('wid');
 		$where["wid"] = $wid;
		$res = Db::table('kt_wework_groupmsg')
					->where($where)
					->page($page,$size)
                    ->json(["content","staffer","adjunct_data"])
                    ->order("ctime DESC")
					->filter(function($data){
                        $data["size"] = count($data["adjunct_data"]);
                        $data["alert_status"] = 0;
						$tag_info = Db::table("kt_wework_staff")->where(["id"=>$data["staffer"]])->field("name")->select()->toArray();
						$data["staffer_name"] = array_column($tag_info, "name");
                        $data["detail"] = self::getData($data["id"]);
                        if($data["detail"]["delivery_groups"] >= 1) $data["alert_status"] = 1;
						return $data;
					});
		    if($times) $res = $res->whereBetweenTime('send_time', $times[0], $times[1]);
		    if($name) $res = $res->whereLike('name','%'.$name.'%');
			$datas['count'] = $res->count();
			$datas['item'] = $res->select()->toArray();
			$datas['page'] = $page;
			$datas['size'] = $size;
		return $datas;
	}

	/**
    * 获取员工userid
    */
    static public function getUser($id){
    	$res = Db::table('kt_wework_staff')->field("userid")->find($id);
    	return $res;
    }

    /**
    * 初始化数据
    */
    static public function getMsg($id){
    	$res = Db::table('kt_wework_groupmsg')->find($id);
    	$res["staffer"] = json_decode($res["staffer"],1);
        $res["content"] = json_decode($res["content"],1);
    	$res["adjunct_data"] = json_decode($res["adjunct_data"],1);
    	$res["groups"] = self::getGroup($res["staffer"]);
    	return $res;
    }

    static public function addDetails($wid,$msg_id,$res,$staff_id){
        $data["wid"] = $wid;
        $data["pid"] = $res;
        $data["msg_id"] = $msg_id;
        $data["staff_id"] = $staff_id;
        $res = Db::table('kt_wework_groupmsg_detail')->insertGetId($data);

        return $res;
    }

    /**
    * 同步记录入库
    */
    static public function addDetail($send_list,$wid,$msg){
        $staff_id = $msg["staff_id"];
    	foreach($send_list as $send){
    		$detail = Db::table('kt_wework_groupmsg_detail')->where(["wid"=>$wid,"chat_id"=>$send["chat_id"],"msg_id"=>$msg["id"],"staff_id"=>$staff_id])->find();
    		$data["wid"] = $wid;
    		$data["pid"] = $msg["pid"];
    		$data["msg_id"] = $msg["id"];
    		$data["chat_id"] = $send["chat_id"];
    		$data["staff_id"] = $staff_id;
    		if(isset($send["status"])) $data["status"] = $send["status"];
            if(isset($send["send_time"])) $data["send_time"] = date("Y-m-d H:i:s",$send["send_time"]);
    		if($detail)Db::table('kt_wework_groupmsg_detail')->where(["id"=>$detail["id"]])->save($data);
            if(!$detail){
                $detail = Db::table('kt_wework_groupmsg_detail')->where(["wid"=>$wid,"msg_id"=>$msg["id"],"staff_id"=>$staff_id,"status"=>0])->find();
                if($detail)Db::table('kt_wework_groupmsg_detail')->where(["wid"=>$wid,"msg_id"=>$msg["id"],"staff_id"=>$staff_id,"status"=>0])->save($data);
                if(!$detail)Db::table('kt_wework_groupmsg_detail')->insertGetId($data);
            }
		}
		return true;
    	
    }

    /**
    * 详情客户群接收详情
    */
    static public function getGroupAll($id,$name=NULL,$status){
    	if($status == 1) $where["d.status"] = 1;
    	if($status == 2) $where["d.status"] = 0;
    	if($status == 3) $where["d.status"] = 2;
		$where["d.pid"] = $id;
    	$res = Db::table("kt_wework_groupmsg_detail")
    					->alias("d")
    					->leftjoin(['kt_wework_group'=>'g'],'d.chat_id = g.chat_id')
						->where($where)
						->field("d.id,d.status,g.name,d.staff_id,g.create_time,g.chat_id");
		if($name) $res = $res->whereLike('g.name','%'.$name.'%');
					$res = $res->filter(function($data){
	    					$data["staff"] = Db::table("kt_wework_staff")->field("name,avatar,department")->json(["department"])->find(["id"=>$data["staff_id"]]);
                            $data["size"] = Db::table("kt_wework_group_member")->where(["chat_id"=>$data["chat_id"],"status"=>1])->count();
                            $department = Db::table("kt_wework_department")->where(["id"=>$data["staff"]["department"]])->field("department_name")->select()->toArray();
                            $data["staff"]["department"] = array_column($department,"department_name");  
                            if($data["create_time"])$data["create_time"] = date("Y-m-d H:i:s",$data["create_time"]);
	    					return $data;
	    				})->select()
						->toArray();
		return $res;
	}

	/**
    * 群主发送详情
    */
    static public function getUserAll($id,$staff_id=NULL,$status=NULL){
    	$where["pid"] = $id;
    	if($status == 1)$where["status"] = 1;
    	if($status == 2)$where["status"] = 0;
    	if($staff_id)$where["staff_id"] = $staff_id;
    	$res = Db::table("kt_wework_groupmsgid")
    					->where($where)
    					->field("id,status,staff_id,pid")
    					->filter(function($data) use($id){
                            $data["staff"] = Db::table("kt_wework_staff")->field("name,avatar,department")->find(["id"=>$data["staff_id"]]);
	    					$department = Db::table("kt_wework_department")->where(["id"=>json_decode($data["staff"]["department"],1)])->field("department_name")->select()->toArray();
                            $data["department"] = array_column($department,"department_name");
	    					$data["group_size"] = Db::table("kt_wework_groupmsg_detail")->where(["pid"=>$id])->count();
	    					$data["send_size"] = Db::table("kt_wework_groupmsg_detail")->where(["pid"=>$id,"status"=>1])->count();
                            $time = Db::table("kt_wework_groupmsg_detail")->where(["msg_id"=>$data["id"],"status"=>1])->field("send_time")->find();
                            $data["time"] = "-";
                            if($time)$data["time"] = $time["send_time"];
	    					return $data;
	    				})
	    				->select()
	    				->toArray();
	    return $res;
    }

    
    static public function msgUpd($id){
    	$res = Db::table("kt_wework_groupmsg")->where(["id"=>$id])->update(["status"=>1]);
	    return $res;
    }

    
    static public function msgSet($id){
    	$res = Db::table("kt_wework_groupmsgid")->where(["id"=>$id])->update(["status"=>1]);
	    return $res;
    }

    
    static public function updateTime($id){
    	$res = Db::table("kt_wework_groupmsg")->where(["id"=>$id])->update(["update_time"=>date("Y-m-d H:i:s",time())]);
	    return $res;
    }

    //获取id列表中所有的userid
    static public function getStaffer($staff){
    	$res = Db::table('kt_wework_staff')->where(["id"=>$staff])->field("userid,id")->select()->toArray();
    	return $res;
    }

	/*
    * 获取详情中详细数据
    * send_staff 已发送群主数量
    * delivery_groups 已送达群聊数量
    * delivery_group 未发送群主数量
    * unsent_group 未送达群聊数量
    */
    static public function getData($id){
 		$wid = Session::get('wid');
 		$send_staff = Db::table("kt_wework_groupmsgid")->where(["wid"=>$wid,"pid"=>$id,"status"=>1])->count();
 		$delivery_group = Db::table("kt_wework_groupmsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>0])->count();
 		$delivery_groups = Db::table("kt_wework_groupmsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>1])->count();
 		$unsent_group = Db::table("kt_wework_groupmsg_detail")->where(["wid"=>$wid,"pid"=>$id])->where("status",">","1")->count();
        $data["send_staff"] = $send_staff;
        $data["delivery_group"] = $delivery_group;
        $data["delivery_groups"] = $delivery_groups;
        $data["unsent_group"] = $unsent_group;
        return $data;
    }

    static public function getDetailList($id){
        $wid = Session::get('wid');
        $res = Db::table("kt_wework_groupmsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>0])->group("staff_id")->field("staff_id")->select()->toArray();
        return $res;
    }


    /**
    * 获取部门下员工列表
    * 
    */
    static public function departmentAll($department,$staffer){
        $wid = Session::get('wid');
        $where["wid"] = $wid;
        $where["id"] = $department;
        $res = Db::table("kt_wework_department")
                        ->where($where)
                        ->field("department_id,department_name")
                        ->select()
                        ->toArray();
        $data = Db::table("kt_wework_staff");
        foreach($res as $value){
            $where = [];
            $where[0] = ["wid","=",$wid];
            $where[0] = ["department","like","%{$value['department_id']}%"];
            $where[0] = ["department_name","like","%\"{$value['department_name']}\"%"];
            $data = $data->whereOr($where);
        }
        $data = $data->field("id")
                        ->select()
                        ->toArray();
        return array_unique(array_merge(array_column($data,"id"),$staffer));
    }

    /**
	 * 获取全部成员id
	 * @return 
	 */
 	static public function getAll(){
 		$wid = Session::get('wid');
 		$where["wid"] = $wid;
 		$res = Db::table("kt_wework_staff")
 					->where($where)
 					->field("id,userid")
 					->filter(function($data){
 						$data["detail_count"] = Db::table("kt_wework_customer")->where(["staff_id"=>$data["id"],"status"=>0])->count();
 						return $data;
 					})
 					->select()
 					->toArray();
		return $res;
	}

	/**
	 * 创建客户群发
	 * @param name 名称
	 * @param staffer 员工数组
	 * @param content 文本数据
	 * @param adjunct_data 附件
	 * @param send_status 是否立即发送
	 * @param send_time 发送时间
	 * @return
 	*/
	static public function addMsg($name,$staffer,$content,$adjunct_data=NULL,$send_status,$send_time=NULL){
        $wid = Session::get('wid');
        $data["wid"] = $wid;
        $data["name"] = $name;
        $data["send_status"] = $send_status;
        $data["send_time"] = empty($send_time)?$send_time:date("Y-m-d H:i:s",time());
        $data["staffer"] = json_encode($staffer,320);
        $data["content"] = json_encode($content,320);
        $data["adjunct_data"] = json_encode($adjunct_data,320);
        $data["ctime"] = date("Y-m-d H:i:s",time());
        $res = Db::table('kt_wework_groupmsg')->insertGetId($data);
        return $res;
    }

	/**
	 * 客户群群发结果入库
	 * @param staff_id 群主id
	 * @param pid 所属群发id
	 * @param msgid 群发id
	 * @param send_size 发送时间
	 * @return
 	*/
	static public function addMsgid($staff_id,$pid,$msgid,$wid=NULL){
		$wid = Session::get('wid')?:$wid;
 		$data["wid"] = $wid;
 		$data["staff_id"] = $staff_id;
 		$data["pid"] = $pid;
 		$data["msgid"] = $msgid;
 		$data["ctime"] = date("Y-m-d H:i:s",time());
        $set = Db::table('kt_wework_groupmsgid')->where(["pid"=>$pid,"staff_id"=>$staff_id])->find();
 		$res = 0;
        if(!$set)$res = Db::table('kt_wework_groupmsgid')->insertGetId($data);
        
        return $res;
	}

	/**
	* 获取所有群聊
	* @param  staffer 员工集合
	*/
	static public function getGroup($staffer){
		$wid = Session::get('wid');
		$where["wid"] = $wid;
		$where["staff_id"] = $staffer;

		$res = Db::table('kt_wework_group')->where($where)->field("chat_id,owner,name")->select()->toArray();
 		return $res;
	}

	//组装 换迎语附件 数据
    static public function assembleOther($otherData,$wid){
        $data = [];
        foreach ($otherData as $other) {
            switch ($other['type']) {
                case '1':
                    $data[] = [
                        'msgtype'=>'image',
                        'image'=>[
                            'media_id' => QyWechatApi::mediaUpload($wid,$other['url'],'image')['media_id'],
                        ]
                    ];
                    break;
                case '2':
                    $data[] = [
                        'msgtype'=>'link',
                        'link'=>[
                            'title' => $other['link_title'],
                            'picurl' => $other['link_picurl'],
                            'desc' => $other['link_desc'],
                            'url' => $other['link_url'],
                        ]
                    ];
                    break;
                case '3':
                    $data[] = [
                        'msgtype'=>'miniprogram',
                        'miniprogram'=>[
                            'title' => $other['miniprogram_title'],
                            'pic_media_id' => QyWechatApi::mediaUpload($wid,$other['miniprogram_imgurl'],'image')['media_id'],
                            'appid' => $other['miniprogram_appid'],
                            'page' => $other['miniprogram_page'],
                        ]
                    ];
                    break;
            }
        }
        return $data;
    }
}